package com.princess.demok.ui.demo

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.princess.baselib.utils.LogUtils
import com.princess.baselib.utils.setOnClickListenerWithTrigger
import com.princess.demok.R
import com.princess.demok.base.view.MyBaseActivity
import com.princess.demok.ui.demo.model.NameViewModel
import kotlinx.android.synthetic.main.activity_livedata.*

/**
 * @author: xha
 * @date: 2021/4/9 11:35
 * @Description:
 */
class LiveDataActivity : MyBaseActivity() {

    companion object {
        @JvmStatic
        fun start(
            context: Activity
        ) {
            val starter = Intent(context, LiveDataActivity::class.java)
            context.startActivity(starter)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_livedata
    }

    private val myNameViewModel by lazy { ViewModelProvider(this).get(NameViewModel::class.java) }

    override fun initOnCreate() {

        myNameViewModel.currentName().observe(this, Observer {
                tvShowLiveData.text = it
        })

        myNameViewModel.nameList().observe(this, Observer {
            if (it != null) {
                for (item in it) {
                    LogUtils.i(item)
                    tvShowLiveData.text = item
                }
            }
        })

        // Create the observer which updates the UI.
        val nameObserver = Observer<String> { newName ->
            // Update the UI, in this case, a TextView.
            tvShowLiveData.text = newName
        }

        // Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
        myNameViewModel.currentName.observe(this, nameObserver)

    }

    override fun initOnClickerListener() {
        super.initOnClickerListener()

        tvChange.setOnClickListenerWithTrigger {
//            myNameViewModel.currentName().setValue("Hubery")
            val anotherName = "John Doe"
            myNameViewModel.currentName.setValue(anotherName)
        }

        tvList.setOnClickListenerWithTrigger {
            var nameList = ArrayList<String>()
            for (i in 0..9) {
                nameList.add("Hubery<$i>")
            }
            myNameViewModel.nameList().setValue(nameList)
        }

    }


}